package pers.fjl.test.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import pers.fjl.common.constant.MessageConstant;
import pers.fjl.common.entity.QueryPageBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import pers.fjl.common.po.Role;
import pers.fjl.test.dao.UserDao;
import pers.fjl.test.service.UserItemService;
import pers.fjl.common.po.User;
import pers.fjl.common.vo.UserItem;

import javax.annotation.Resource;

@Slf4j
@Service
public class UserItemServiceImpl extends ServiceImpl<UserDao, User> implements UserItemService {

    @Resource
    private UserItemService userItemService;
    @Resource
    private UserDao userDao;
    @Resource
    private BCryptPasswordEncoder encoder;

    @Cacheable(value = {"UserMap"})
    public Page<User> findPage(QueryPageBean queryPageBean) {
        //设置分页条件
        Page<User> page = new Page<>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //设置查询条件
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like(queryPageBean.getQueryString() != null, "username", queryPageBean.getQueryString());
        return userDao.selectPage(page, wrapper);
    }

    public boolean UserExist(String username) {//搜索用户名是否存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.select("1");
        wrapper.eq("username", username).last("limit 1");
        return userDao.selectCount(wrapper) != 0;
    }

    @Cacheable(value = {"User"})
    public User findById(String userId) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", userId);
        if (userDao.selectOne(wrapper) == null) {
            return null;
        }
        return userDao.selectOne(wrapper);
    }

    @Override
    @CacheEvict(value = {"UserMap"}, allEntries = true)
    public boolean addUser(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        log.info("addUser.user.getUsername():[{}]", user.getUsername());
        if (userItemService.UserExist(user.getUsername())) {
            throw new RuntimeException("用户名已被注册");
        }
        user.setDataStatus(MessageConstant.UserAble);
        user.setPassword(encoder.encode(user.getPassword()));
//        user.setId(50);
        userItemService.save(user);
        return true;
    }

    @Override
    public boolean forbid(String id) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id)
                .select("data_status");
        User user = new User();
        int count = userDao.update(user, wrapper);
        if (count < 1) {
            throw new RuntimeException("禁用用户失败");
        } else {
            return true;
        }
    }

    @CacheEvict(value = {"UserMap"}, allEntries = true)
    public boolean deleteById(String userId) {
        int count = userDao.deleteById(userId);
        if (count < 1) {
            throw new RuntimeException("删除用户失败");
        } else {
            return true;
        }
    }

    @CacheEvict(value = {"UserMap"}, allEntries = true)
    public boolean updateUser(User user) {
        if (userDao.updateById(user) >= 0) {
            return true;
        }
        throw new RuntimeException("用户更新失败，请稍后再试");
    }

    @Override
    public boolean userStateChanged(String id, boolean dataStatus) {
        boolean flag = update(new UpdateWrapper<User>()
                .set("data_status", dataStatus)
                .eq("id", id));
        return flag;
    }

    public User login(User user) throws RuntimeException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.select("id", "username", "password", "data_status", "rid");
        wrapper.eq("username", user.getUsername());
        //登录的用户
        User login_user = userDao.selectOne(wrapper);
        log.debug("login_user:[{}]", login_user.toString());
        if (!encoder.matches(user.getPassword(), login_user.getPassword())) {
            throw new RuntimeException("用户名或密码不正确，登录失败");
        }
        if (login_user.isDataStatus() == (MessageConstant.UserDisable)) {
            throw new RuntimeException("用户已被禁用,登录失败");
        }
        update(new UpdateWrapper<User>()
//               .set("last_time", new Date())
                .set("last_ip", user.getLastIp())
                .eq("username", login_user.getUsername()));

        return login_user;
    }
}
